package com.haizhi.user;


import com.haizhi.util.Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

// 定义用户访问接口
@Service
public class UserInfoServiceImpl implements UserInfoService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private final UserInfoRepository userInfoRepository;

    @Autowired
    public UserInfoServiceImpl(UserInfoRepository userInfoRepository) {
        this.userInfoRepository = userInfoRepository;
    }

    @Override
    public boolean insertUser(String username, String password) {

        if (username == null || Objects.equals(username, "") ||
                password == null || Objects.equals(password, "")) {
            logger.warn("用户密码信息不合法....");
            return false;
        }

        UserInfo userInfo = new UserInfo();

        userInfo.setUsername(username);
        userInfo.setPassword(password);
        userInfo.setCreateTime(Tools.getCurrentTime());
        userInfo.setUpdateTime(Tools.getCurrentTime());

        try {
            this.userInfoRepository.insert(userInfo);
        } catch (Exception e) {
            logger.error("插入用户信息异常: username = {} password = {}", username, password);
            logger.error("Exception:", e);
            return false;
        }

        return true;
    }

    @Override
    public boolean deleteUser(String username) {

        try {
            this.userInfoRepository.delete(username);
        } catch (Exception e) {
            logger.error("删除用户信息异常: username = {}", username);
            logger.error("Exception:", e);
            return false;
        }
        return true;
    }

    @Override
    public boolean updatePassword(String username, String password) {
        try {

            UserInfo userInfo = this.userInfoRepository.findOne(username);
            if (userInfo == null) {
                logger.warn("没有找到用户信息...");
                return false;
            }

            userInfo.setPassword(password);
            userInfo.setUpdateTime(Tools.getCurrentTime());
            this.userInfoRepository.save(userInfo);
        } catch (Exception e) {
            logger.error("更新密码信息异常: username = {} password = {}", username, password);
            logger.error("Exception:", e);
            return false;
        }

        return true;
    }

    @Override
    public void deleteAll() {
        logger.warn("删除全部用户信息...");
        this.userInfoRepository.deleteAll();
    }

    @Override
    public List<UserInfo> findAll() {
        return this.userInfoRepository.findAll();
    }
}
